<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Daily as DailyModel;
use addons\qingdongams\model\DailyDraft;
use addons\qingdongams\model\DailyRead;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\FormField;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\Message;
use think\Db;
use think\Exception;
/**
 * 工作报告接口
 */
class Daily extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//创建
	public function createDaily() {
		$params = $this->request->post();
        $result = FormField::checkFields(DailyModel::getTypeName($params['type']), $params);
        if ($result !== true) {
            $this->error($result);
        }
		Db::startTrans();
		try {
			$params['create_staff_id'] = $this->auth->id;
			$dailyId                   = DailyModel::createDaily($params);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		$this->success('创建工作报告成功');
	}


	//获取
	public function getList() {
		$limit         = input("limit/d", 10);
		$is_read       = input('is_read', 0);
		$staff_id       = input('staff_id', 0);
		$type       = input('type', 0);

		$where         = [];
		$where['create_staff_id'] = ['in', Staff::getMyStaffIds()];
		if($staff_id){
			$where['create_staff_id']=$staff_id;
		}
		if($type){
			$where['type']=$type;
		}
		$staff_id             = $this->auth->id;
		if ($is_read == 1) {//已读
			$ids         = DailyRead::where(['staff_id' => $staff_id])->column('daily_id');
			$where['id'] = ['in', $ids];
		} elseif ($is_read == 2) {//未读
			$ids         = DailyRead::where(['staff_id' => $staff_id])->column('daily_id');
			$where['id'] = ['not in', $ids];
		}
		$records = DailyModel::where($where)->with([
			'staff',
			'read' => function ($query) use ($staff_id) {
				$query->where(['staff_id' => $staff_id]);
			}
		])->order('id desc')->paginate($limit)->toArray();

		$data = $records['data'];
		foreach ($data as $k => $v) {
			if (!empty($v['read'])) {
				$v['is_read'] = 1;
			} else {
				$v['is_read'] = 0;
			}
			$data[$k] = $v;
		}
		$this->success('请求成功', [
			'total'        => $records['total'],
			'per_page'     => $records['per_page'],
			'current_page' => $records['current_page'],
			'last_page'    => $records['last_page'],
			'data'         => $data
		]);

		$this->success('请求成功', $records);
	}


	//获取详情
	public function getDailyDetail() {
		$id = input('id');
		if (empty($id)) {
			$this->error('参数不能为空');
		}
		$record = DailyModel::where(['id' => $id])->with([
			'staff',
		])->find();
		if (empty($record)) {
			$this->error('记录不存在');
		}

		$record               = $record->toArray();
		$reminds_id           = $record['reminds_id'];
		$reminds_id           = explode(',', $reminds_id);
		$names                = \addons\qingdongams\model\Staff::where(['id' => ['in', $reminds_id],'status'=>1])->column('name');
		$record['staff_name'] = implode(',', $names);

        $other = $record['other']?:[];
        $record = array_merge($record, $other);
        $record = Form::getDataDetail(DailyModel::getTypeName($record['type']), $record);
		//标记通知已读
		//添加阅读记录
		DailyRead::addRead($id, $this->auth->id);
        //标记通知已读
        Message::setRead(Message::DAILY_TYPE, $id, $this->auth->id);

		$this->success('请求成功', $record);
	}


    //获取工作报告已读 未读
    public function getDailyRead()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $daily = DailyModel::where(['id' => $id])->find();
        if (empty($daily)) {
            $this->error('记录不存在');
        }
        $create_staff_id = $daily['create_staff_id'];

        $read = DailyRead::where(['daily_id' => $id])->group('staff_id')->field('id,staff_id')->with(['staff'])->select();
        $staffIds = [];
        foreach ($read as $v) {
            $staffIds[] = $v['staff_id'];
        }
        //全部可看数据的人
        $allids = explode(',', $daily->reminds_id);
        $not_ids = array_diff($allids, $staffIds);

        $notRead = Staff::where(['id' => ['in', $not_ids],'status'=>1])
            ->field('id,name,img')->select();
        $this->success('请求成功', ['read' => $read, 'not_read' => $notRead]);
    }

    //草稿创建成功
    public function daily_draft()
    {
        $params = $this->request->post();

        Db::startTrans();
        try {
            $params['create_staff_id'] = $this->auth->id;
            //自定义字段
            $other = [];
            foreach ($params as $name => $val) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
                unset($params[$name]);
            }
            $params['other'] = json_encode($other);
            $where['create_staff_id'] = $this->auth->id;
            $where['type'] = $params['type'];
            $info = DailyDraft::where($where)->find();
            if ($info) {
                $result = DailyDraft::where(array('id' => $info['id']))->update($params);
            } else {
                $result = DailyDraft::create($params);
            }

            if (false === $result) {
                // 验证失败 输出错误信息
                throw new Exception('草稿保存失败');
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('草稿保存成功');
    }

    //获取详情
    public function getDailyDraftDetail()
    {
        $type = input('type');
        if (!$type) {
            $this->error('参数不正确');
        }
        $where['create_staff_id'] = $this->auth->id;
        $where['type'] = $type;
        $record = DailyDraft::where($where)->find();
        if (empty($record)) {
            $this->success('记录不存在');
        }
        switch ($record['type']) {
            case '日报':
                $record['type_index'] = 0;
                break;
            case '周报':
                $record['type_index'] = 1;
                break;
            case '月报':
                $record['type_index'] = 2;
                break;
            case '季报':
                $record['type_index'] = 3;
                break;
            case '年报':
                $record['type_index'] = 4;
                break;
            default:
                $record['type_index'] = 0;
                break;
        }
        $record = $record->toArray();
        $reminds_id = $record['reminds_id'];
        $reminds_id = explode(',', $reminds_id);
        $names = Staff::where(['id' => ['in', $reminds_id],'status'=>1])->field('id,img,name,post')->select();
        $record['staff_info'] = $names;

        $other = $record['other']?:[];
        $record = array_merge($record, $other);

        $this->success('请求成功', $record);
    }


    //修改工作报告
    public function updateDaily()
    {
        $params = $this->request->post();
        if(empty($params['id'])){
            $this->error('参数不能为空');
        }

        Db::startTrans();
        try {
            $dailyId = DailyModel::updateDaily($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('创建工作报告成功');
    }

}
